$(function () {
    //https://www.cnblogs.com/litter/p/6371210.html
    $('[name="switch"]').bootstrapSwitch({
        onText: "非0工时项目",
        offText: "全部项目",
        onColor: "success",
        offColor: "info",
        size: "small",// (mini/small/normal/large)
        onSwitchChange: function (event, state) {
            if (state == true) {
                one(1)
            } else {
                one(0)
            }
        }
    }).trigger('switchChange.bootstrapSwitch');

    // 按照周/月维度统计
    $('[name="switch_scope"]').bootstrapSwitch({
        onText: "按月统计",
        offText: "按周统计",
        onColor: "success",
        offColor: "info",
        size: "small",// (mini/small/normal/large)
        onSwitchChange: function (event, state) {
            initDatePicker();
        }
    })/*.trigger('switchChange.bootstrapSwitch')*/;


    bindTwoBtn();
    initDatePicker();
    bindThreeBtn();
    $("#three-submit").trigger("click");

});


function bindTwoBtn() {
    $("#two-submit").on("click", function () {
        let formJson = $("#two-submit").closest("form").formJson();
        console.log(formJson);
        if (!common.validateForm(formJson)) {
            $.alert('请选择项目和开始结束月份');
            return false;
        }
        two(formJson);
        return true;
    })
}

function bindThreeBtn() {
    $("#three-submit").on("click", function () {
        let formJson = $("#three-submit").closest("form").formJson();
        console.log(formJson);
        if (!common.validateForm(formJson)) {
            $.alert('请选择要统计工时的周');
            return false;
        }
        three(formJson);
        return true;
    })
}

//项目工时柱状图概览
function one(usedTime) {
    let url = ctx + "stats/overview";
    $.ajax(url, {
        dataType: "json",
        data: {usedTime: usedTime}
    }).done(function (data) {
        if (data.code == 0) {
            __init(data.data);
        } else {
            $.alert("获取统计工时失败");
        }
    });

    function __init(data) {
        // 基于准备好的dom，初始化echarts实例
        var myChart = echarts.init(document.getElementById('one'));

        /*
         * 柱状图
         * 1. 总工时 当年工时 当月工时
         * 2. 项目列表
         * 3. 项目列表对应：总工时 当年工时 当月工时
         */
        // 指定图表的配置项和数据
        var option = {
            title: {
                text: data.xAxisData.length + '个项目 当月/当年/总工时汇总柱状图(人天)',
            },
            tooltip: {},
            legend: {
                data: data.legendData
            },
            xAxis: {
                type: 'category',
                axisLabel: {
                    interval: 0,//代表显示所有x轴标签显示
                    rotate: -45, //代表逆时针旋转45度
                },
                data: data.xAxisData
            },
            yAxis: {},
            series: data.series
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
        myChart.on('click', function (params) {
            let projectName = params.name;
            console.info("click project: " + projectName);
            selectByProjectName(projectName);

        });
        // 手动触发点击第一个柱体的事件
        selectByProjectName(data.xAxisData[0]);
    }

}

function selectByProjectName(projectName) {
    if (!projectName) return;
    // 首先找到所有匹配的选项
    var $options = $('#two-projectId option');
    // 遍历所有选项，根据文本内容设置选中状态
    $options.each(function () {
        if ($(this).text() === projectName) {
            $(this).prop('selected', true); // 设置为选中状态
            $('#two-projectId').val($(this).val()).trigger('change');
            $("#two-submit").trigger("click");
        }
    });
}

//项目月度工时折线图

function two(data) {
    let url = ctx + "stats/monthLine";

    $.ajax(url, {
        dataType: "json",
        data: data
    }).done(function (data) {
        if (data.code == 0) {
            __init(data.data);
        } else {
            $.alert("获取项目月度工时失败");
        }
    });
    __init("");

    function __init(data) {
        // 基于准备好的dom，初始化echarts实例
        var myChart = echarts.init(document.getElementById('two'));

        //折线图改为柱状图
        var option = {
            title: {
                text: $("#two-projectId option:selected").text() + " 月度工时(人天)柱状图",
            },
            tooltip: {},
            xAxis: {
                type: 'category',
                data: data.xAxisData
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    data: data.seriesData,
                    type: 'bar',
                    showBackground: true,
                    barMaxWidth: 30,
                    backgroundStyle: {
                        color: 'rgba(180, 180, 180, 0.2)'
                    }
                }
            ]
        };
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
    }
}


function three(data) {
    let url = ctx + "stats/weekBar";

    $.ajax(url, {
        dataType: "json",
        data: data
    }).done(function (data) {
        if (data.code == 0) {
            __init(data.data);
        } else {
            $.alert("实时获取工时失败");
        }
    });
    __init("");

    function __init(data) {
        // 基于准备好的dom，初始化echarts实例
        var myChart = echarts.init(document.getElementById('three'));
        if (!data) return;

        var scope = $('[name="switch_scope"]').bootstrapSwitch('state')  ? '月' : '周';;
        //折线图改为柱状图
        var option = {
            title: {
                text: "实时统计人员 ["+ scope +"] 工时(人天)柱状图:" + data.xAxisData.length + "人",
            },
            tooltip: {
                formatter: function (params) {
                    let tooltipContent = params.name + " " + params.value + '<br/>'; // 柱状图对应的名称
                    tooltipContent += data.otherInfo[params.dataIndex]; // 自定义信息，params[0].value 可以根据需要获取
                    return tooltipContent;
                }
            },
            xAxis: {
                type: 'category',
                axisLabel: {
                    interval: 0,//代表显示所有x轴标签显示
                    rotate: -45, //代表逆时针旋转45度
                },
                data: data.xAxisData
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    data: data.seriesData,
                    type: 'bar',
                    showBackground: true,
                    barMaxWidth: 30,
                    backgroundStyle: {
                        color: 'rgba(180, 180, 180, 0.2)'
                    }
                }
            ]
        };
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
    }
}

function setWeekRange(date) {
    var isWeek = !$('[name="switch_scope"]').bootstrapSwitch('state');
    var scope = isWeek ? 'isoWeek' : 'month';
    var startOfWeek = date.clone().startOf(scope);
    var endOfWeek = date.clone().endOf(scope);
    $('#startWeekDate').val(startOfWeek.format('YYYY-MM-DD'));
    $('#endWeekDate').val(endOfWeek.format('YYYY-MM-DD'));
    console.log("Selected  " + scope + ": " + startOfWeek.format('YYYY-MM-DD') + " to " + endOfWeek.format('YYYY-MM-DD'));

    //此处自动触发提交表单按钮
    $("#three-submit").trigger("click");
}


function initDatePicker() {
    $('#weekPicker').daterangepicker({
        locale: {
            format: 'YYYY-MM-DD'
        },
        singleDatePicker: true,
        autoApply: true,
        showCustomRangeLabel: false,
        drops: 'right', // 控制弹出位置
        isInvalidDate: function (date) {
            // Disable selection of individual days
            return false;
        },
    }, function (start) {
        setWeekRange(start);
    });

    $('#weekPicker').on('apply.daterangepicker', function (ev, picker) {
        setWeekRange(picker.startDate);
    });

    // Set the initial value to the current week
    setWeekRange(moment());

    $("#weekRangePicker").on("click", function () {
        $('#weekPicker').trigger("click");
    });
}